<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>添加商品</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/static/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/static/css/frame.css">

    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <style>
        .out-box{
            background-color: #f3f3f3;
            padding: 15px 0;
            margin-bottom: 20px;
        }
        .layui-upload-img { width: 90px; height: 90px; margin: 0; }
        .pic-more { width:100%; margin: 10px 0px 0px 0px;}
        .pic-more li { width:90px; float: left; margin-right: 5px;}
        .pic-more li .layui-input { display: initial; }
        .pic-more li a { position: absolute; top: 0; display: block; }
        .pic-more li a i { font-size: 24px; background-color: #008800; }
        #slide-pc-priview .item_img img{ width: 90px; height: 90px;}
        #slide-pc-priview li{position: relative;}
        #slide-pc-priview li .operate{ color: #000; display: none;}
        #slide-pc-priview li .toleft{ position: absolute;top: 40px; left: 1px; cursor:pointer;}
        #slide-pc-priview li .toright{ position: absolute;top: 40px; right: 1px;cursor:pointer;}
        #slide-pc-priview li .close{position: absolute;top: 5px; right: 5px;cursor:pointer;}
        #slide-pc-priview li:hover .operate{ display: block;}
    
        #slide-pc-priview1 .item_img img{ width: 90px; height: 90px;}
        #slide-pc-priview1 li{position: relative;}
        #slide-pc-priview1 li .operate{ color: #000; display: none;}
        #slide-pc-priview1 li .toleft{ position: absolute;top: 40px; left: 1px; cursor:pointer;}
        #slide-pc-priview1 li .toright{ position: absolute;top: 40px; right: 1px;cursor:pointer;}
        #slide-pc-priview1 li .close{position: absolute;top: 5px; right: 5px;cursor:pointer;}
        #slide-pc-priview1 li:hover .operate{ display: block;}
    </style>
</head>
<body>           
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
    <legend>添加商品</legend>
</fieldset>

<form class="layui-form layui-form-pane" action="" lay-filter="example" style="padding: 20px">
    <div class="layui-form-item">
        <label class="layui-form-label">商品类型</label>
        <div class="layui-input-inline" style="width: 40%">
            <select name="type" lay-filter="type">
                <option value="">-- 请选择商品类型 --</option>
                <option value="1">普通商品</option>
                <option value="2">佣金商品</option>
                <option value="3">红包商品</option>
                <option value="4">积分商品</option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">商品分类</label>
        <div class="layui-input-inline" style="width: 40%">
            <select name="cate_id" id="cate_id">
                {foreach $cate_list as $k => $v}
                <option value="{$v.id}">{$v.name}</option>
                {/foreach}
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">商品名称</label>
        <div class="layui-input-inline" style="width: 40%">
            <input type="text" name="name" lay-verify="name" autocomplete="off" placeholder="请输入商品名称" class="layui-input">
        </div>
        <div class="layui-form-mid layui-word-aux">
            <span style="color: red">*</span> 长度1-100个字符
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">商品描述</label>
        <div class="layui-input-inline" style="width: 40%">
            <input type="text" name="describe" lay-verify="describe" autocomplete="off" placeholder="请输入商品描述" class="layui-input">
        </div>
        <div class="layui-form-mid layui-word-aux">
            <span style="color: red">*</span> 长度1-100个字符
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">价格</label>
        <div class="layui-input-inline" style="width: 40%">
            <input type="number" name="price" lay-verify="price" autocomplete="off" placeholder="请输入价格" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">原价</label>
        <div class="layui-input-inline" style="width: 40%">
            <input type="number" name="price_origin" lay-verify="price_origin" autocomplete="off" placeholder="请输入原价" class="layui-input">
        </div>
    </div>
    
    <div class="layui-form-item" id="price_brokerage" style="display: none;">
        <label class="layui-form-label">佣金价格</label>
        <div class="layui-input-inline" style="width: 40%">
            <input type="number" name="price_brokerage" lay-verify="price_brokerage" autocomplete="off" placeholder="请输入佣金价格" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item" id="brokerage_ratio" style="display: none;">
        <label class="layui-form-label">返利佣金</label>
        <div class="layui-input-inline" style="width: 40%">
            <input type="number" name="brokerage_ratio" lay-verify="brokerage_ratio" autocomplete="off" placeholder="请输入返利佣金参数" class="layui-input">
        </div>
        <div class="layui-form-mid layui-word-aux">
            <span style="color: red">*</span> 比如：0.5表示50%（售价的N%）
        </div>
    </div>

    <div class="layui-form-item" id="point_ratio" style="display: none;">
        <label class="layui-form-label">返利积分</label>
        <div class="layui-input-inline" style="width: 40%">
            <input type="number" name="point_ratio" lay-verify="point_ratio" autocomplete="off" placeholder="请输入返利积分参数" class="layui-input">
        </div>
        <div class="layui-form-mid layui-word-aux">
            <span style="color: red">*</span> 比如：0.5表示50%（售价的N%）
        </div>
    </div>

    <div class="layui-form-item" id="money_red" style="display: none;">
        <label class="layui-form-label">返利红包</label>
        <div class="layui-input-inline" style="width: 40%">
            <input type="number" name="money_red" lay-verify="money_red" autocomplete="off" placeholder="请输入返利红包" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item" style="display: flex;">
        <label class="layui-form-label">缩略图</label>
        <div class="layui-input-inline">
            <div class="fup_files">
                <input type="file" name="small_img" onchange="fuploads($(this))">
                <img src="" class="img" name="img" width="100%" height="100%" style="display: none" />
            </div>
        </div>
    </div>

    <div class="layui-form-item" id="pics">
        <div class="layui-form-label">商品轮播图</div>
        <div class="layui-input-block" style="width: 70%;">
            <div class="layui-upload">
                <button type="button" class="layui-btn layui-btn-primary pull-left" id="slide-pc">选择多图</button>
                <div class="pic-more">
                    <ul class="pic-more-upload-list" id="slide-pc-priview"></ul>
                </div>
            </div>
        </div>
    </div>

    <div class="layui-form-item" id="pics">
        <div class="layui-form-label">商品详情图</div>
        <div class="layui-input-block" style="width: 70%;">
            <div class="layui-upload">
                <button type="button" class="layui-btn layui-btn-primary pull-left" id="slide-pc1">选择多图</button>
                <div class="pic-more">
                    <ul class="pic-more-upload-list" id="slide-pc-priview1"></ul>
                </div>
            </div>
        </div>
    </div>

    <div class="layui-form-item" id="pics">
        <div class="layui-form-label">规格</div>
        <div class="layui-input-block" style="width: 70%;">
            <div class="layui-upload">
                <button type="button" class="layui-btn layui-btn-primary pull-left" id="specs_add">添加规格</button>
                <table class="layui-table">
                    <thead>
                        <tr>
                            <th>属性</th>
                            <th>属性值</th>
                            <th>价格</th>
                        </tr> 
                    </thead>
                    <tbody id="specs">
                        <tr>
                            <td>
                                <select name="sku[]"  lay-filter="sku">
                                    <option value="">-- 请选择属性 --</option>
                                    {foreach $sku_list as $k => $v}
                                    <option value="{$v.id}">{$v.name}</option>
                                    {/foreach}
                                </select>
                            </td>
                            <td>
                                <select name="sku_value[]" id="sku_value">
                                </select>
                            </td>
                            <td><input type="number" name="price_specs[]" lay-verify="price_specs" autocomplete="off" placeholder="请输入价格" class="layui-input"></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button type="submit" class="layui-btn" lay-submit="" lay-filter="submit">立即提交</button>
            <a href="javascript:history.back(-1)" class="layui-btn layui-btn-primary">返回</a>
        </div>
    </div>
</form>
          
<script src="/static/layui/layui.js" charset="utf-8"></script>

<script>
    //图片上传
    function fuploads(f){
        var nameAll = f[0].files[0].type;
        var name = nameAll.split("/");
        
        if(name[0] != 'image'){
            layer.msg('上传类型错误', {icon: 2});
        }else{
            var url = window.URL.createObjectURL(f[0].files[0]);  // 得到bolb对象路径，可当成普通的文件路径一样使用
            f.next("img").css('display', 'block');
            f.next("img").attr('src', url);
        }
    }

    var goodsImgBanner = [];
    layui.use('upload', function(){
        var $ = layui.jquery;
        var upload = layui.upload;

        upload.render({
            elem: '#slide-pc',
            url: '{:url("goods/imgUpMany")}',
            size: 50000,
            exts: 'jpg|png|jpeg',
            multiple: true,
            before: function(obj) {
                layer.msg('图片上传中...', {
                    icon: 16,
                    shade: 0.01,
                    time: 0
                })
            },
            done: function(res) {
                goodsImgBanner.push(res.data);

                layer.close(layer.msg());  // 关闭上传提示窗口

                if(res.status == 0) {
                    return layer.msg(res.msg);
                }

                $('#slide-pc-priview').append('<li class="item_img"><div class="operate"><i class="toleft layui-icon"></i><i class="toright layui-icon"></i><i  class="close layui-icon"></i></div><img src="' + res.data + '" class="img bannerimg" ><input type="hidden" name="pc_src[]" class="input2" value="' + res.data + '" /></li>');
            }
        });
    });

    var goodsImgShow = [];
    layui.use('upload', function(){
        var $ = layui.jquery;
        var upload = layui.upload;

        upload.render({
            elem: '#slide-pc1',
            url: '{:url("goods/imgUpMany")}',
            size: 50000,
            exts: 'jpg|png|jpeg',
            multiple: true,
            before: function(obj) {
                layer.msg('图片上传中...', {
                    icon: 16,
                    shade: 0.01,
                    time: 0
                })
            },
            done: function(res) {
                goodsImgShow.push(res.data);

                layer.close(layer.msg());  // 关闭上传提示窗口

                if(res.status == 0) {
                    return layer.msg(res.msg);
                }

                $('#slide-pc-priview1').append('<li class="item_img"><div class="operate"><i class="toleft layui-icon"></i><i class="toright layui-icon"></i><i  class="close layui-icon"></i></div><img src="' + res.data + '" class="img detimg" ><input type="hidden" name="pc_src[]" class="input2" value="' + res.data + '" /></li>');
            }
        });
    });
        
    //点击多图上传的X,删除当前的图片
    $("body").on("click",".close",function(){
        var that = $(this).closest("li");
        that.remove();
    });

    //多图上传点击<>左右移动图片
    $("body").on("click",".pic-more ul li .toleft",function(){
        var li_index=$(this).closest("li").index();
        if(li_index>=1){
            $(this).closest("li").insertBefore($(this).closest("ul").find("li").eq(Number(li_index)-1));
        }
    });
    $("body").on("click",".pic-more ul li .toright",function(){
        var li_index=$(this).closest("li").index();
        $(this).closest("li").insertAfter($(this).closest("ul").find("li").eq(Number(li_index)+1));
    });

    layui.use(['form'], function(){
        var form = layui.form, layer = layui.layer;
        
        $("body").on("click","#specs_add",function(){
            let str = '<tr><td><select name="sku[]" lay-filter="sku"><option value="">-- 请选择属性 --</option>';

            $.ajax({
                type: 'post',
                url: '{:url("Goods/spec_sku")}',
                dataType:'json',
                success:function(res){
                    res.data.forEach(val => {
                        str += `<option value="${val.id}">${val.name}</option>`;
                    });

                    str += `</select></td><td><select name="sku_value[]" lay-filter="sku_value"></select></td><td><input type="number" name="price_specs[]" lay-filter="price_specs" placeholder="请输入价格" class="layui-input"></td></tr>`;

                    $('#specs').append(str);
                    form.render()
                }
            })
        });

        // 监听提交
        form.on('submit(submit)', function(data){
            // console.log(data.field)
            let sku_list = [];

            for(key in data.field){
                if(key.indexOf("sku[") >= 0 || key.indexOf("sku_value") >= 0 || key.indexOf("price_specs") >= 0){
                    let object = {};
                    object[key] = data.field[key];
                    sku_list.push(object)
                } 
            }

            // if(!data.field.status){
            //     data.field.status = '0'
            // }

            let bannerImg = JSON.stringify([...$(".bannerimg")].map((val,index) => {
                return {
                    url: $(val).attr("src"),
                    sort: index+1
                }
            }))

            let showImg = JSON.stringify([...$(".detimg")].map((val,index) => {
                return {
                    url: $(val).attr("src"),
                    sort: index+1
                }
            }))

            let formData = new FormData();
            let img = $("input[name='small_img");

            formData.append('type', data.field.type);
            formData.append('name', data.field.name);
            formData.append('describe', data.field.describe);
            formData.append('price', data.field.price);
            formData.append('price_origin', data.field.price_origin);
            formData.append('price_brokerage', data.field.price_brokerage);
            formData.append('brokerage_ratio', data.field.brokerage_ratio);
            formData.append('point_ratio', data.field.point_ratio);
            formData.append('money_red', data.field.money_red);
            formData.append('small_img', img[0].files[0]);
            formData.append('banner_img', bannerImg);
            formData.append('show_img', showImg);
            formData.append('sku_list', JSON.stringify(sku_list));

            if(!data.field.cate_id){
                data.field.cate_id = 0
            }
            
            formData.append('cate_id', data.field.cate_id);

            // 加载中样式... 
            let loading = layer.msg('正在添加，请稍后...', {icon: 16, shade: 0.3, time:0});

            $.ajax({
                url:'{:url("Goods/goods_add_data")}',
                data:formData,
                contentType: false,  // 必须false才会自动加上正确的Content-Type
                processData: false,
                type:"post",
                dataType:'json',
                success:function(res){
                    layer.close(loading);
                    if(res.code == 0){
                        layer.msg(res.msg, {icon: 1,time: 1500}, function(){
                            history.back(-1);
                        });
                    }else{
                        layer.msg(res.msg, {icon: 2});
                    }
                },
                error:function(res){
                    layer.msg(res.msg, {icon: 2});
                }
            })

            return false;
        });

        // 下拉框事件
        form.on('select(type)', function(data){
            // console.log(data.elem); //得到select原始DOM对象
            // console.log(data.value); //得到被选中的值
            // console.log(data.othis); //得到美化后的DOM对象

            if(data.value == 2){
                $('#price_brokerage').show();
                $('#brokerage_ratio').show();
                $('#money_red').hide();
                $('#point_ratio').hide();
            }else if(data.value == 3){
                $('#price_brokerage').hide();
                $('#brokerage_ratio').hide();
                $('#money_red').show();
                $('#point_ratio').hide();
            }else if(data.value == 4){
                $('#price_brokerage').hide();
                $('#brokerage_ratio').hide();
                $('#money_red').hide();
                $('#point_ratio').show();
            }else{
                $('#price_brokerage').hide();
                $('#brokerage_ratio').hide();
                $('#money_red').hide();
                $('#point_ratio').hide();
            }
        });

        // 下拉框事件
        form.on('select(sku)', function(data){
            // console.log(data.elem); //得到select原始DOM对象
            // console.log(data.value); //得到被选中的值
            // console.log(data.othis); //得到美化后的DOM对象

            $.ajax({
                type: 'post',
                url: '{:url("Goods/sku_value")}',
                data: {sku_id:data.value},
                dataType:'json',
                success:function(res){
                    data.othis.parent().next().children(1).html('<option value="">-- 请选择属性值 --</option>');
                    // $("#sku_value").html('<option value="">-- 请选择属性值 --</option>');

                    res.data.forEach(val => {
                        data.othis.parent().next().children(1).append(`<option value="${val.id}">${val.name}</option>`)
                    })

                    form.render()
                },error:function(msg){
                    layer.msg('数据异常', {icon: 2});
                }
            })
        });
    });
</script>
</body>
</html>